const fs = require('fs')
const {Feed} = require('feed') // 3rd deps

var feed = {}

var defaultFeed = {
    title: "CONF: Fucker Fucker Feed Title",
    description: "CONF: Your website feed description",
    id: "http://localhost:6969/",
    link: "http://localhost:6969/",
    copyright: "MIT",
    generator: "blog_builder",
    author: {
        name: "fucker fucker",
        email: "1876056356 At Fucking Tencent QQ dot COM",
        link: "gitee.com/eeppee"
    }
}


function init() {
    var builder = require('./builder')// builde.js that module as builder
    if (!fs.existsSync(`${builder.dirs.data}/feedconfig.json`))
        fs.writeFileSync(`${builder.dirs.data}/feedconfig.json`, JSON.stringify(defaultFeed))
}

function build() {
    var builder = require('./builder')
    var feedConfigFile = `${builder.dirs.data}/feedconfig.json`

    if (!fs.existsSync(feedConfigFile))
        return

    var feedconfig = JSON.parse(fs.readFileSync(feedConfigFile))

    feed = new Feed(feedconfig)

    builder.getPages().forEach(page => {
        if (!page.draft && (page.index || page.index === undefined)) {
            feed.addItem(
                {
                    title: page.title,
                    id: page.url,
                    link: feedconfig.link + page.url,
                    description: page.description,
                    date: new Date(page.date)
                }
            )        
        }
    })

    fs.writeFileSync(`${builder.dirs.out}/rss.xml`, feed.rss2()) // using feed.rss2() write method ?
}

function getFeed() {
    return feed
}

module.exports = {
    init,
    build,
    getFeed,
}